package fosu.generated.controller;

import fosu.generated.common.Result;
import fosu.generated.common.ResultCode;
import fosu.generated.dto.LoginDTO;
import fosu.generated.dto.LoginResponseDTO;
import fosu.generated.dto.RegisterDTO;
import fosu.generated.entity.User;
import fosu.generated.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 用户控制器
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "*")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Result<Map<String, Object>> login(@RequestBody LoginDTO loginDTO) {
        logger.info("用户登录请求，用户名: {}", loginDTO.getUsername());

        try {
            User user = userService.login(loginDTO);

            Map<String, Object> data = new HashMap<>();
            data.put("token", "mock_token_" + user.getId());
            data.put("userId", user.getId());
            data.put("userName", user.getUsername());
            data.put("role", user.getRole());

            logger.info("登录成功，用户ID: {}", user.getId());
            return Result.success(data);

        } catch (RuntimeException e) {
            logger.error("登录失败: {}", e.getMessage());
            return Result.error(ResultCode.USERNAME_OR_PASSWORD_ERROR);
        } catch (Exception e) {
            logger.error("登录异常", e);
            return Result.error();
        }
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Result<Void> register(@RequestBody RegisterDTO registerDTO) {
        logger.info("用户注册请求，用户名: {}", registerDTO.getUsername());

        try {
            userService.register(registerDTO);
            logger.info("注册成功，用户名: {}", registerDTO.getUsername());
            return Result.success("注册成功");

        } catch (RuntimeException e) {
            logger.error("注册失败: {}", e.getMessage());
            if (e.getMessage().contains("用户名已存在")) {
                return Result.error(ResultCode.USER_ALREADY_EXISTS);
            } else if (e.getMessage().contains("手机号已注册")) {
                return Result.error(ResultCode.PHONE_ALREADY_REGISTERED);
            }
            return Result.error(e.getMessage());
        } catch (Exception e) {
            logger.error("注册异常", e);
            return Result.error();
        }
    }

    /**
     * 忘记密码
     */
    @PostMapping("/forgot")
    public Result<Map<String, String>> forgotPassword(@RequestBody Map<String, String> request) {
        logger.info("找回密码请求，用户名: {}", request.get("username"));

        try {
            String password = userService.forgotPassword(
                    request.get("username"),
                    request.get("phone")
            );

            Map<String, String> data = new HashMap<>();
            data.put("password", password);

            logger.info("密码找回成功");
            return Result.success(data);

        } catch (RuntimeException e) {
            logger.error("密码找回失败: {}", e.getMessage());
            return Result.error(ResultCode.USERNAME_OR_PHONE_MISMATCH);
        } catch (Exception e) {
            logger.error("密码找回异常", e);
            return Result.error();
        }
    }
}
